package com.anycl.customer.dao.impl;

import com.anycl.customer.dao.AdminUserRepository;
import com.anycl.customer.entity.AdminUser;
import com.anycl.customer.utils.JDBCUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

@Slf4j
public class AdminUserRepositoryImpl implements AdminUserRepository {
    @Override
    public int signIn(AdminUser user) {
        Connection conn = null;
        PreparedStatement pst = null;
        String sql = "insert into user(username, password, status) values(?,?,?)";
        int num = 0;
        try {
            conn = JDBCUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1, user.getUsername());
            pst.setString(2, user.getPassword());
            pst.setInt(3, user.getStatus());
            num = pst.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(pst, conn);
        }
        return num;
    }

    @Override
    public AdminUser getUserByUsername(String username) {
        AdminUser user = null;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "select id, username, password, status from user where username = \'" + username + "\'";
        log.info(sql);
        try {
            conn = JDBCUtil.getConnection();
            pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            rs = pst.executeQuery();
            while (rs.next()) {
                user = new AdminUser();
                user.setId(rs.getInt(1));
                user.setUsername(rs.getString(2));
                user.setPassword(rs.getString(3));
                user.setStatus(rs.getInt(4));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(rs, pst, conn);
        }
        return user;
    }
}
